package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountFoundException;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BadArgsException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public Result update(EmployeeDTO employeeDTO) {
        //修改过的账号不能重复。如果账号没有变动，则可以修改
        //1.根据修改过的账号去查询，看是否有记录
        Employee dbEmp = employeeMapper.getByUsername(employeeDTO.getUsername());
        if(null == dbEmp || dbEmp.getId().equals(employeeDTO.getId())) {
            //2.有，再判断对应的记录是否是自己本身
            //可以改
            Employee employee = new Employee();
            BeanUtils.copyProperties(employeeDTO, employee);

            //=====================如下代码已经通过AOP功能实现了自动填充=========================
            //employee.setUpdateTime(LocalDateTime.now());
            ////从ThreadLocal中获取数据
            //Long empId = BaseContext.getCurrentId();
            //employee.setUpdateUser(empId);
            employeeMapper.update(employee);
        } else {
            //不能改
            throw new AccountFoundException("账号已经存在，请更换！");
        }
        return Result.success();
    }

    @Override
    public Result<Employee> findById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //敏感数据处理
        employee.setPassword("");
        return Result.success(employee);
    }

    @Override
    @Transactional
    public Result startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                ////=====================如下代码已经通过AOP功能实现了自动填充=========================
                //.updateTime(LocalDateTime.now())
                //.updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.update(employee);
        return Result.success();
    }

    @Override
    public Result<PageResult> pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1.校验参数
        int page = employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize();
        if(employeePageQueryDTO == null
                || page <= 0
                || pageSize <= 0) {
            throw new BadArgsException("非法参数");
        }

        // 2.处理业务
        String name = employeePageQueryDTO.getName();
        employeePageQueryDTO.setName(name == null ? "" : name.trim());
        System.out.println("--->" + employeePageQueryDTO);;

        //分页
        PageHelper.startPage(page, pageSize);
        Page<Employee> result = employeeMapper.getCondition(employeePageQueryDTO);
        // 3.封装数据
        PageResult pageResult = new PageResult(result.getTotal(), result.getResult());
        return Result.success(pageResult);
    }

    @Override
    @Transactional
    public Result add(EmployeeDTO employeeDTO) {
        // 1.校验参数
        if(employeeDTO == null
            || StringUtils.isBlank(employeeDTO.getUsername()) //null or "" --> true
            || StringUtils.isBlank(employeeDTO.getName())
            || StringUtils.isBlank(employeeDTO.getPhone())) {
            throw new BadArgsException("非法参数");
        }
        // 2.处理业务
        //根据账号查询用员工是否存在？
        Employee employee = employeeMapper.getByUsername(employeeDTO.getUsername());
        if(null != employee) {
            throw new AccountFoundException("账号已经存在，请更换！");
        }
        employee = new Employee();
        //属性拷贝：属性名与类型完全相同，才能拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        //=====================如下代码已经通过AOP功能实现了自动填充=========================
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        ////从ThreadLocal中获取数据
        //Long empId = BaseContext.getCurrentId();
        //employee.setCreateUser(empId);  //先留着
        //employee.setUpdateUser(empId);

        //补全实体
        employeeMapper.insert(employee);

        // 3.封装数据
        return Result.success();
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Result<EmployeeLoginVO> login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //引用类型比较应该使用equals
        if (StatusConstant.DISABLE.equals(employee.getStatus())) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                 .build();

        //3、返回实体对象
        return Result.success(employeeLoginVO);
    }

}